iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 9
0

Desciption:
Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321
Example 2:

Input: -123
Output: -321
Example 3:

Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.


Explantation:
題意如標題。

  • 正數 123 倒著回來 321
  • 負數 -123 ,負號保留 接著一樣倒著回來
  • 倒著回來 如果第一個數是0則 ignore 不顯示

Note: 考慮overflow問題 超過range 則 return 0


Language: python

import math
def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        pass
 
    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass
        return False
class Solution(object):

    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        max = math.pow(2,31) - 1
        min = (math.pow(2,31))*(-1)
        print "min:" , min
        print "MAX:",int(max)
        print "x=",x
        print(type(x))
        flag = 0
        if x < 0 :
            x = -x
            flag = 1
        tmp = x
        ans = []
        flag2 = 0
        while tmp!=0 :
            if (tmp%10 or flag2==1) !=0 :
                ans.append(tmp%10)
                flag2 = 1
            tmp = tmp / 10
        print(ans)
        final_ans = ""
        for i in range(len(ans)):
            if is_number(ans[i]):
                final_ans+=str(ans[i])
        print "check: ",final_ans
        #print "test:",float(final_ans)
        
        if x == 0:
            return "0"
        elif (int(final_ans)*(-1)) < min:
            return "0"
        elif flag == 1:
            return "-"+final_ans
        elif x == 0 :
            return "0"
        elif int(final_ans) > max:
            return "0"
        #elif int(final_ans) < min:
        #    return 0
        else:
            return final_ans

Submitted Code: 6 months ago


上一篇
LeetCode 8. String to Integer (atoi)
下一篇
(Medium) 6. ZigZag Conversion
系列文
刷刷題 or Alan Becker's game 製作 is a question 30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言